package com.csj.DesignPattern.singleton.demo7;

// 懒汉式
// 静态内部类
public class SingletonReadResolve {

    private static boolean flag = false;

    private SingletonReadResolve() {
        synchronized (Singleton.class) {
            if (!flag) {
                flag = true;
            } else {
                throw new RuntimeException("单例构造器禁止反射调用");
            }
        }
    }

    private static class SingletonHolder {
        private static final SingletonReadResolve INSTANCE = new SingletonReadResolve();
    }

    public static SingletonReadResolve getInstance() {
        return SingletonHolder.INSTANCE;
    }

    //进行反序列化时，会调用该方法，返回单例对象，避免重新创建对象
    /*
    if (obj != null &&
            handles.lookupException(passHandle) == null &&
            desc.hasReadResolveMethod())
        {
            Object rep = desc.invokeReadResolve(obj);
            如果有readResolve方法，则返回该方法返回的对象
     */
    public Object readResolve() {
        return SingletonHolder.INSTANCE;
    }

}
